<template>
  <view>
    <view class="container">
      <scroll-view class="chat-container" :scroll-y="true" :scroll-into-view="scrollToId">
        <view class="box">
          <view class="header">
            <text class="title">提问指引</text>
          </view>
          <view class="content">
            <view class="guidance" v-for="(item, index) in guidance" :key="index">
              <view class="dot"></view>
              <text class="text">{{ item.text }}</text>
            </view>
          </view>
        </view>
        <view v-for="(msg, index) in messages" :key="index" :id="'msg-' + index" :class="['chat-box', msg.role]">
          <image v-if="msg.role === 'ai'" class="head-img" :src="aiHeadImg" />
          <text class="chat-text">{{ msg.content }}</text>
          <image v-if="msg.role === 'me'" class="head-img" :src="meHeadImg" />
        </view>
<!--        <view v-if="loading" class="loading-state">-->
<!--          <text>正在处理中...</text>-->
<!--        </view>-->
      </scroll-view>
    </view>

    <!-- 评论输入框 -->
    <view class="comment-tool">
      <view class="wrap">
        <view style="height: 60rpx; display: flex; align-items: center">
          <input ref="lfinput" type="text" :placeholder="placeholder" class="comment-input" @blur="onBlur" @focus="focusEvent" v-model="form.content" :disabled="loading" confirm-type="send" @confirm="addComment" />
        </view>
        <u-button @click="addComment" :disabled="isSubmitD || loading" :custom-style="btnStyle" type="success">
          发送
        </u-button>
      </view>
    </view>
  </view>
</template>
<script>
const API_URL = 'https://api.coze.cn';
const BOT_ID = '7436925329324949545';
const AUTH_TOKEN = 'pat_CAqbr0pNWztSkTcm4B1IPAHtvfGKyOajFoPem3YtwlhnjGKtw1ldBFN29gRnIyYY';
const HEADER = {
  'Authorization': `Bearer ${AUTH_TOKEN}`,
  'Content-Type': 'application/json'
};

export default {
  name: "index",
  data() {
    return {
      placeholder: '说点什么...',
      isSubmitD: false,
      form: {
        content: '',
      },
      btnStyle: {
        borderRadius: '100rpx',
        color: "#fff",
        backgroundColor: '#000000',
        width: '166rpx',
        height: '60rpx',
        fontSize: '30rpx'
      },
      guidance: [],
      aiHeadImg: '',
      meHeadImg: '', // 用户的头像
      messages: [], // 存储所有消息
      conversationId: '', // 会话ID
      chatId: '', // 对话ID
      user_id: '', // 用户ID
      loading: false, // AI处理状态
      scrollToId: '', // 滚动到的ID
      inProgressMessageAdded: false // 标志位，判断是否已经添加了“正在思考中...”的消息
    }
  },
  onLoad(options) {
    // 获取传递的参数
    if (options && options.data) {
      const data = JSON.parse(options.data)
      this.title = data.title;
      this.guidance = data.desc.split(/\n/g).map(text => ({text}));
      this.aiHeadImg = options.img
      // 设置导航栏标题
      this.setNavigationBarTitle(data.title);
    }
    // const userInfo = uni.getStorageSync("userInfo");
    // if (userInfo) {
    this.user_id = '12333333333';
    this.meHeadImg = require('@/static/images/ai/ai04.jpg');
    // }
    this.createConversation();
  },
  methods: {
    setNavigationBarTitle(title) {
      uni.setNavigationBarTitle({
        title
      });
    },
    createConversation() {
      uni.request({
        url: `${API_URL}/v1/conversation/create`,
        method: 'POST',
        header: HEADER,
        success: (res) => {
          if (res.data.code === 0) {
            this.conversationId = res.data.data.id;
          }
        }
      });
    },
    getChatStatus() {
      uni.request({
        url: `${API_URL}/v3/chat/retrieve?chat_id=${this.chatId}&conversation_id=${this.conversationId}`,
        method: 'GET',
        header: HEADER,
        success: (res) => {
          if (res.data.code === 0) {
            const status = res.data.data.status;
            if (status === 'completed') {
              this.loading = false;
              this.fetchMessage();
            } else if (status === 'in_progress') {
              this.loading = true;
              if (!this.inProgressMessageAdded) {
                this.addInProgressMessage(); // 添加“正在思考中...”的消息
              }
              setTimeout(() => this.getChatStatus(), 2000); // 每2秒检查一次状态
            }
          }
        }
      });
    },
    addInProgressMessage() {
      this.messages.push({
        role: 'ai',
        content: '正在思考中...'
      });
      this.scrollToLatestMessage();
      this.inProgressMessageAdded = true; // 标记已经添加了“正在思考中...”的消息
    },
    fetchMessage() {
      uni.request({
        url: `${API_URL}/v3/chat/message/list?chat_id=${this.chatId}&conversation_id=${this.conversationId}`,
        method: 'GET',
        header: HEADER,
        success: (res) => {
          if (res.data.code === 0) {
            const assistantMessage = res.data.data.find(item => item.role === 'assistant' && item.type === 'answer');
            if (assistantMessage) {
              const lastMessage = this.messages[this.messages.length - 1];
              if (lastMessage.role === 'ai' && lastMessage.content === '正在思考中...') {
                lastMessage.content = assistantMessage.content; // 更新“正在思考中...”的消息
              } else {
                this.messages.push({
                  role: 'ai',
                  content: assistantMessage.content
                });
              }
              this.scrollToLatestMessage();
            }
          }
        }
      });
    },
    addComment() {
      if (this.form.content.trim() === '') return;
      this.messages.push({
        role: 'me',
        content: this.form.content
      });
      this.inProgressMessageAdded = false
      this.isSubmitD = true;
      this.loading = true;
      uni.request({
        url: `${API_URL}/v3/chat?conversation_id=${this.conversationId}`,
        method: 'POST',
        header: HEADER,
        data: {
          bot_id: BOT_ID,
          user_id: this.user_id,
          stream: false,
          auto_save_history: true,
          additional_messages: [
            {
              role: 'user',
              content: this.form.content,
              content_type: 'text'
            }
          ]
        },
        success: (res) => {
          if (res.data.code === 0) {
            this.chatId = res.data.data.id;
            this.getChatStatus();
          }
        },
        complete: () => {
          this.isSubmitD = false;
          this.form.content = '';
          this.scrollToLatestMessage();
        }
      });
    },
    scrollToLatestMessage() {
      setTimeout(() => {
        this.scrollToId = 'msg-' + (this.messages.length - 1);
      }, 100); // 延迟100毫秒
    },
    onBlur() {
      this.placeholder = '留下你的精彩评论...';
      this.focus = false;
    },
    focusEvent(event) {
      this.placeholder = '说点什么...';
    },
  }
}
</script>



<style scoped lang="scss">
/* 全局样式 */
page {
  background-color: #f7f7f7;
}

/* 评论tool */
.comment-tool {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #fff;
  padding: 20rpx;
  z-index: 999;

  .wrap {
    padding: 3px;
    padding-left: 10px;
    display: flex;
    background-color: #f5f5f5;
    border-radius: 20px;

    input {
      //width: 480rpx !important;
    }
  }

  .img-wrap {
    position: relative;
    width: 80rpx;
    height: 80rpx;
    margin: 20rpx;
    margin-bottom: 0;
    color: #fff;

    .comment-img {
      border-radius: 8rpx;
      width: 80rpx;
      height: 80rpx;
    }

    .mask {
      border-radius: 8rpx;
      z-index: 10;
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.2);
      font-size: 24rpx;
      display: flex;
      align-items: flex-end;
      justify-content: center;
    }

    .del {
      z-index: 10;
      position: absolute;
      right: -10rpx;
      top: -10rpx;
      width: 30rpx;
      height: 30rpx;
      border-radius: 30rpx;
      background-color: rgba(0, 0, 0, 0.5);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
    }
  }
}

.comment-tool textarea {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  min-height: 40rpx;
}

.comment-tool .u-btn {
  margin-left: 10rpx;
}

.comment-input {
  height: 60rpx;
  font-size: 28rpx;
  font-weight: 500;
  line-height: 60rpx;
  width: 500rpx;
  margin-right: 20rpx;
}

/* 最外层容器 */
.container {
  //padding: 30px 10px; /* 上下30px，左右10px */
  display: flex;
  justify-content: center; /* 水平居中 */
  flex-direction: column;
  padding-bottom: 110rpx;
}

/* 圆角盒子 */
.box {
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 小外阴影 */
  width: 100%;
  max-width: 400px; /* 可以根据需要调整最大宽度 */
  //padding: 20px; /* 内边距 */
  position: relative;
  margin-bottom: 20px;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #d4f4d4; /* 浅绿色背景 */
  padding: 10px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  margin-bottom: 5px; /* 与内容之间的间距 */
}

/* 标题 */
.title {
  font-size: 16px;
  color: #333;
  font-weight: bold;
  margin: 0;
}

/* 拖动柄 */
.drag-handle {
  width: 20px;
  height: 20px;
  background-color: #8bc34a; /* 深绿色 */
  border-radius: 50%;
  margin-left: 10px;
}

/* 内容 */
.content {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  padding-left: 10px;
  padding-right: 10px;
}

/* 引导项 */
.guidance {
  display: flex;
  align-items: center; /* 垂直居中 */
  margin-bottom: 10px; /* 每句话之间的间距 */
}

/* 红色小点 */
.dot {
  width: 4px;
  height: 4px;
  background-color: #fa4545;
  border-radius: 50%;
  margin-right: 10px; /* 与文字之间的间距 */
}

/* 文字 */
.text {
  font-size: 14px;
  color: #666;
}

/* 聊天容器 */
.chat-container {
  // max-height: 500px;
  overflow-y: auto;
  //padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  //margin-top: 20px;
}

/* 聊天框 */
.chat-box {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;

  &.me {
    justify-content: flex-end;
    .head-img {
      margin-right: 0;
      margin-left: 10px;
    }
  }

  &.ai {
    justify-content: flex-start;
  }

  .head-img {
    width: 50rpx;
    height: 50rpx;
    border-radius: 50%;
    margin-right: 10px;
  }

  .chat-text {
    max-width: 70%;
    padding: 10px;
    border-radius: 10px;
    background-color: #d4f4d4;
    font-size: 14px;
    color: #333;
  }
}

/* 加载状态 */
.loading-state {
  text-align: center;
  margin-top: 20px;
  color: #999;
}
</style>
